import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

export async function GET(req: NextRequest, { params }: { params: { groupId: string } }) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { groupId } = params;

    // 1. 验证用户是否是群成员
    const membership = await prisma.groupMember.findUnique({
      where: {
        groupId_userId: {
          groupId,
          userId,
        },
      },
    });

    if (!membership) {
      return NextResponse.json({ error: '你不是该群组成员，无权查看' }, { status: 403 });
    }

    // 2. 获取群组信息及成员列表
    const groupDetails = await prisma.group.findUnique({
      where: { id: groupId },
      include: {
        members: {
          include: {
            user: {
              select: {
                id: true,
                nickname: true,
                avatar: true,
              },
            },
          },
        },
      },
    });

    if (!groupDetails) {
      return NextResponse.json({ error: '群组不存在' }, { status: 404 });
    }

    return NextResponse.json(groupDetails);
  } catch (error) {
    console.error('获取群组详情失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}

export async function PUT(req: NextRequest, { params }: { params: { groupId: string } }) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { groupId } = params;
    const { name, description } = await req.json();

    // 1. 获取群组并验证所有权
    const group = await prisma.group.findUnique({
      where: { id: groupId },
    });

    if (!group) {
      return NextResponse.json({ error: '群组不存在' }, { status: 404 });
    }

    if (group.ownerId !== userId) {
      return NextResponse.json({ error: '只有群主才能修改群组信息' }, { status: 403 });
    }

    // 2. 更新群组信息
    const dataToUpdate: { name?: string, description?: string } = {};
    if (name) dataToUpdate.name = name;
    if (description !== undefined) dataToUpdate.description = description;

    if (Object.keys(dataToUpdate).length === 0) {
      return NextResponse.json({ error: '没有提供需要更新的字段' }, { status: 400 });
    }

    const updatedGroup = await prisma.group.update({
      where: { id: groupId },
      data: dataToUpdate,
    });

    return NextResponse.json(updatedGroup);

  } catch (error) {
    console.error('更新群组信息失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 